
module Api

  module V1

    class OrdersController < Api::V1::ApplicationController

      define_action :log_cgj_result, {
        name: '记录窗管家测量结果',
        description: '记录窗管家测量结果, 记得传UA: YY_web',
        params: {
          required: ['order_no', 'amount', 'papers'],
          properties: {
            order_no: {
              type: 'string',
              description: '商城订单号'
            },
            amount: {
              description: '总额'
            },
            papers: {
              description: '图纸'
            }
          }
        },
        return: {
          type: 'object',
          properties: {
            error_code: {
              type: 'integer',
              description: ''
            },
            data: {
              type: 'object',
              properties: {
                message: {
                  type: 'string'
                }
              }
            }
          }
        }
      } do
        @order = Order.find_by_order_no! params[:order_no]
        history_amount = params[:amount].to_f / 100

        if @order.survey_pending?
          Order.transaction do
            @order.complete_survey!

            SmsService.tail_payment(@order.user.mobile, @order.order_no)

            @order.order_histories << OrderHistory.new(amount: history_amount, content: params[:papers], status: @order.workflow_state)
          end
        else
          history = OrderHistory.find_by_order_id_and_status!(@order.id, "survey_completed")
          history.amount = history_amount
          history.content = params[:papers]
          history.save!
        end
        update_amount(@order, history_amount)
      end

    private

    def update_amount order, history_amount
      payment = order.payment
      payment.total_money = history_amount
      payment.save!

      order.total_money = history_amount
      order.save!
    end

    end

  end

end
